<template>


  <BasicTable @register="registerTable">
    <template #form-classifyId="{ model, field }">
      <a-cascader v-model:value="model[field]" :options="options" placeholder="请选择"
        :fieldNames="{ label: 'classifyName', value: 'classifyId' }" />
    </template>
    <template #toolbar>
      <!-- <a-button type="primary" @click="handleCreate">新增</a-button>
        <a-button type="primary" :disabled="selectedRowKeys.length === 0" @click="handleBatchDelete">批量删除</a-button> -->
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <TableAction :actions="createActions(record)" />
      </template>
    </template>
  </BasicTable>
  <!-- <ModalAddRecord @register="registerModal" @success="handleSuccess" /> -->

</template>s
<script setup lang="ts">

import { BasicTable, useTable, TableAction, EditRecordRow, ActionItem } from '@/components/Table'
import {

  updateManualEntryRecord,
  // deleteManualEntryList,
} from '@/api/sys/manualEntry'
import {
  getDictListByCodeDay,

  updateDictListByCodeDay

} from '@/api/sys/dataModification'
import { searchFormSchema, columns } from './dayData'
import { ref, onMounted, reactive } from 'vue'
import { useModal } from '@/components/Modal'
import { cloneDeep, last } from 'lodash-es'
import { useMessage } from '@/hooks/web/useMessage'

// import { Key } from 'ant-design-vue/es/table/interface'
import ModalAddRecord from './ModalAddRecord.vue'

import dayjs from 'dayjs'
import { getDictListByCodeAndName } from '@/api/sys/dict'
import { getClassifyTreeByPatent } from '@/api/collection/classify'

defineOptions({ name: '手动修改数据' })



const currentTab = ref('detail')
const { createMessage: msg } = useMessage()
const currentEditKeyRef = ref('')

const options = ref([])
const searchInfo = reactive<Recordable>({})

const changeRadio = (params) => {
  console.log(params);

  // if (params.target.value == 'distribution') {
  //   searchRef.value.handleSearch()
  // }
}
const [registerTable, { reload }] = useTable({
  title: '手动修改数据',
  api: getDictListByCodeDay,
  columns,
  useSearchForm: true,

  // rowKey: 'id',
  searchInfo,
  // 关键配置：启用行编辑模式
  beforeFetch: (params) => {
    if (params.date) {
      const { date, ...others } = params
      return {
        ...others,
        startDateBegin: dayjs(date[0]).startOf('day'),
        startDateEnd: dayjs(date[1]).endOf('day'),
      }
    }
    return params
  },

  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
    autoSubmitOnEnter: true,
  },
  actionColumn: {
    width: 150,
    title: '操作',
    dataIndex: 'action',
  },

})
const [registerModal, { openModal }] = useModal()

function createActions(record: EditRecordRow): ActionItem[] {


  if (!record.editable) {
    console.log(currentEditKeyRef.value == record.id);
    return [
      {
        label: '编辑',
        disabled: currentEditKeyRef.value !== '',
        onClick: handleEdit.bind(null, record),
      },

    ]
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record),
    },
    {
      label: '取消',
      popConfirm: {
        title: '是否取消编辑',
        confirm: handleCancel.bind(null, record),
      },
      // onClick: handleCancel.bind(record),
    },
  ]
}


onMounted(() => {
  getOptions()
})

const getOptions = async () => {
  const parentData = await getDictListByCodeAndName({
    code: 'budget_manage',
    itemName: 'tree_id',
  })
  const data = await getClassifyTreeByPatent({ parentClassifyId: parentData.itemCode })
  options.value = data
}

const handleCancel = (record: EditRecordRow) => {
  currentEditKeyRef.value = ''
  record.onEdit?.(false, false)
}

const handleEdit = (record) => {
  console.log('当前记录ID:', record.id);
  console.log('当前编辑状态:', record.id);

  currentEditKeyRef.value = record.id;

  record.onEdit?.(true); // 触发行编辑

}

const formatEditedData = (editedData, deviceCustomDataVal) => {
  const rowData = cloneDeep(deviceCustomDataVal)
  for (const key in editedData) {
    const [, subKey, field] = key.split(',')

    if (rowData[subKey]) {
      // 编辑的单元格没有值，为null
      if (editedData[key] === null) {
        // 如果原来有值，但是删掉了，要置成0，根据有measureTime判断原来有值
        if (rowData[subKey].measureTime) {
          rowData[subKey][field] = 0
        } else {
          delete rowData[subKey]
        }
      } else {
        // 确保每一条有效数据都有measureTime
        rowData[subKey] = {
          ...rowData[subKey],
          [field]: editedData[key],
          measureTime: subKey,
        }
      }
    }
  }

  return Object.values(rowData)
}

const handleSave = async (record) => {
  // 校验
  const valid = await record.onValid?.()
  if (valid) {
    const editData = record
    console.log(editData);

    // const deviceCustomDataValDTOList = formatEditedData(editData, record.deviceCustomDataVal)
    const data = {
      // id: record.id,
      ...editData
      // deviceCustomDataValDTOList,
    }
    console.log(data, "dadad");

    await updateDictListByCodeDay(data)
    const pass = await record.onEdit?.(false, true)
    if (pass) {
      currentEditKeyRef.value = ''
    }
    msg.success({ content: '数据已保存', key: 'saving' })
    reload()
  } else {
    msg.error({ content: '请填写正确的数据', key: 'saving' })
  }
}


</script>
<style scoped lang="scss">
:deep(.ant-input-number) {
  min-width: 80px;
}
</style>
